package cn.tac.test.spring.boot.redis.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.EventListener;
import redis.embedded.RedisServer;

/**
 * @author tac
 * @since 2018/6/13
 */
@AutoConfigureBefore(RedisAutoConfiguration.class)
public class EmbeddedRedisConfiguration {
    private Logger logger = LoggerFactory.getLogger(EmbeddedRedisConfiguration.class);

    @Bean
    public RedisServer embeddedRedisServer(RedisProperties redisProperties) {
        RedisServer redisServer = RedisServer.builder().setting("maxheap 32M").port(redisProperties.getPort()).build();
        redisServer.start();
        logger.info("embedded redis server is started");
        return redisServer;
    }

    @EventListener
    public void on(ContextClosedEvent event) {
        RedisServer bean = event.getApplicationContext().getBean(RedisServer.class);
        if (bean != null && bean.isActive()) {
            bean.stop();
            logger.info("embedded redis server is closed");
        } else {
            logger.warn("embedded redis server instance is null, make sure you embedded redis process is close");
        }
    }
}
